package com.example.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.enums.ResponseCode;
import com.example.common.handler.BusinessException;
import com.example.order.dto.OrderItem;
import com.example.order.dto.OrderReq;
import com.example.order.entity.User;
import com.example.order.entity.UserOrder;
import com.example.order.mapper.OrderMapper;
import com.example.order.service.IOrderService;
import com.example.order.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * OrderServiceImpl class
 *
 * @author zhangl
 * @date 2023/3/9
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, UserOrder>  implements IOrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private IUserService userService;
    @Override
    public String createOrder(OrderReq orderReq) {
        Long userId = orderReq.getUserId();
        // 校验用户信息
        User user = userService.getUserById(userId);
        if (user == null) {
            throw BusinessException.createException(ResponseCode.FAILED.getCode(),"用户不存在");
        }
        // 生成订单
        List<OrderItem>  orderItems = orderReq.getOrderItems();
        String orderSn = UUID.randomUUID().toString();
        List<UserOrder> userOrders = new ArrayList<UserOrder>();
        orderItems.stream().forEach(orderItem ->{
            UserOrder userOrder = new UserOrder();
            BeanUtils.copyProperties(orderItem,userOrder);
            userOrder.setOrderSn(orderSn);
            orderMapper.insert(userOrder);
        });
        //返回订单id
        return orderSn;
    }
}
